package by.yakusekmaxim.bookgid.services.impl;

import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import by.yakusekmaxim.bookgid.dataaccess.FeedbackDao;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Feedback;
import by.yakusekmaxim.bookgid.datamodel.UserAccount;
import by.yakusekmaxim.bookgid.services.FeedbackService;

@Service
public class FeedbackServiceImpl implements FeedbackService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FeedbackServiceImpl.class);

    @Inject
    private FeedbackDao dao;

    @Override
    public Feedback get(Long id) {
    	Feedback entity = dao.getById(id);
        return entity;
    }

    @Override
    public void saveOrUpdate(Feedback feedback) {
        if (feedback.getId() == null) {
            LOGGER.debug("Save new: {}", feedback);
            dao.insert(feedback);
        } else {
            LOGGER.debug("Update: {}", feedback);
            dao.update(feedback);
        }
    }

    @Override
    public void delete(Feedback feedback) {
        LOGGER.debug("Remove: {}", feedback);
        dao.delete(feedback.getId());

    }

    @Override
    public void deleteAll() {
        LOGGER.debug("Remove all Feedbacks");
        dao.deleteAll();
    }

	@Override
	public Float getEvaluationBook(Book book) {
		Float amounts = null;
		List<Feedback> list = dao.getAllEvaluationsBooks(book);
		if (list != null) {
			amounts = 0F;
			for (Feedback feedback : list) {
				amounts+=feedback.getRating();
			}
			amounts/=list.size();
		}
		return amounts;
	}

	@Override
	public Feedback getBookUserEvaluation(Book book, UserAccount user) {
		List<Feedback> list = dao.getBookUserEvaluation(book, user);
		Feedback feedback = null;
		if (list != null & list.size()!=0) {
			feedback = list.get(0);
		}
		return feedback;
	}

}
